import random
import re

import datetime
from flask import abort, jsonify
from flask import current_app
from flask import request, make_response
from flask import session

from info import constants, db
from info import redis_store
from info.lib.yuntongxun.sms import CCP
from info.models import User
from info.utlis.captcha.captcha import captcha
from info.utlis.response_code import RET
from . import passport_bp


@passport_bp.route('/register', methods=["POST"])
def register():
    """用户注册接口"""
    # 获取参数
    params_json = request.json
    mobile = params_json.get("mobile")
    smscode = params_json.get("smscode")
    password = params_json.get("password")

    # 效验参数
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if not re.match('^1[356789][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误")

    # 逻辑处理
    try:
        real_sms_code = redis_store.get("SMS_%s" %mobile)
        if real_sms_code:
            redis_store.delete("SMS_%s" %mobile)
    except Exception as error:
        current_app.logger.error(error)
        jsonify(errno=RET.DBERR, errmsg="数据库查询异常")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")

    if sms_code != real_sms_code:
        return jsonify(errno=RET.PARAMERR, errmsg="短信验证码填写错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password
    user.last_login = datetime.now()

    try:
        db.session.add(user)
    except Exception as error:
        current_app.logger.error(error)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存到数据库异常")

    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name

    return jsonify(errno=RET.OK, errmsg="注册成功")




@passport_bp.route('/image_code')
def image_code():
    """获取图片验证码"""
    #  获取参数
    imageCodeId = request.args.get("imageCodeId")

    # 效验参数
    if not imageCodeId:
        abort(404)

    # 逻辑处理
    name, text, image = captcha.generate_captcha()

    try:
        redis_store.set("imagecode_%s" %imageCodeId, text, ex=constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as error:
        abort(500)

    response = make_response(image)

    response.headers["Content-Type"] = "image/jpeg"

    return response


@passport_bp.route('/sms_code', methodes=["POST"])
def sms_code():
    """点击发送短信验证码接口"""
    # 获取参数
    params_dict = request.json
    mobile = params_dict.json.get("mobile")
    image_code = params_dict.json.get("image_code")
    image_code_id  = params_dict.json.get("image_code_id")

    # 效验参数
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if not re.match('1[356789][0-9]{9}]', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误")

    # 逻辑处理
    try:
        real_image_code = redis_store.get("imagecode_%s" %image_code_id)

        if real_image_code:
            redis_store.delete(real_image_code)
    except Exception as error:
        current_app.logger.error(error)
        jsonify(errno=RET.DBERR, errmsg="查询数据库出错")

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码过期")

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码填写错误")

    try:
        user = User.query.filter_by(mobile=mobile).first()
        if user:
            return jsonify(errno=RET.DATAEXIST, errmsg="手机号码注册过了")
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")

    sms_code = random.randint(0, 999999)
    sms_code = "06%d" %sms_code
    result = CCP().send_template_sms(mobile, [sms_code, constants.IMAGE_CODE_REDIS_EXPIRES/60], 1)

    if result != 0:
        return jsonify(errno=RET.THIRDERR, errmsg="发送短信验证码失败")

    try:
        redis_store.set("SMS_%s" %mobile, sms_code, ex=constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as error:
        current_app.logger.error(error)
        jsonify(errno=RET.DBERR, errmsg="保存数据库异常")

    return jsonify(errno=RET.OK, errmsg="发送短信验证码成功")

























